/**
 * 获取参数
 * @param name 查询字符串的键名
 * @param pageUrl 页面url 用于兼容服务端渲染的情况
 * @returns {String} 某个查询字符串的值
 *
 */
function getQueryString(name: string, pageUrl?: string): string | null {
  if (pageUrl) {
    var containSearch = pageUrl.split('?')
    var item: string | number = 0,
      re: any = 0
    for (var i = 0, len = containSearch.length; i < len; i++) {
      item = containSearch[i]
      if (item.indexOf('=') !== -1) {
        re = item.match(new RegExp('(^|&)' + name + '=([^&]*)(&|$)'))
        if (re != null) {
          return decodeURIComponent(re[2])
        }
      }
    }
    return null
  } else {
    var after = window.location.search.substr(1) || window.location.hash.split('?')[1]
    if (after) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
      var _re = after.match(reg)
      if (_re != null) {
        return decodeURIComponent(_re[2])
      } else {
        return null
      }
    } else {
      return null
    }
  }
}

/**
 * @param {Array} list
 * @return {Array}
 */
function getModuleFiles(list: any[]) : any[] {
  let modules: any[] = []
  for(let path in list){
    const value = list[path]
    if (isArray(value.default)) {
      modules = [...modules, ...value.default]
    } else {
      modules.push(value.default)
    }
  }
  return modules
}

/**
 * @param {Array} arg
 * @return {boolean}
 */
function isArray(arg: any): boolean {
  if (typeof Array.isArray === 'undefined') {
    return Object.prototype.toString.call(arg) === '[object Array]'
  }
  return Array.isArray(arg)
}


/**
 * 获取uuid
 * @returns {String} 某个查询字符串的值
 */
function getUuid(): string {
  if (typeof crypto === 'object') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID()
    }
    if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
      const callback = (c:any) => {
        const num: number = Number(c)
        return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16)
      }
      return String((1e7 + -1e3 + -4e3 + -8e3 + -1e11)).replace(/[018]/g, callback)
    }
  }
  let timestamp: number = new Date().getTime()
  let perforNow: number = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    let random: number = Math.random() * 16
    if (timestamp > 0) {
      random = (timestamp + random) % 16 | 0
      timestamp = Math.floor(timestamp / 16)
    } else {
      random = (perforNow + random) % 16 | 0
      perforNow = Math.floor(perforNow / 16)
    }
    return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16)
  })
}


export {
  getQueryString,
  getModuleFiles,
  isArray,
  getUuid
}